﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.IO;
using System.Text;
using Newtonsoft.Json.Linq;
using RestFullChatAJAX.Models;
using System.Web;

namespace RestFullChatAJAX.Controllers
{
    public class YahooController : ApiController
    {
        private const String URL_OAUTH_DIRECT = "http://localhost:53220/api/OAuth";
        private const String URL_OAUTH_ACCESS_TOKEN = "http://localhost:53220/api/OAuth/ExchangeRequestToken";
        private const String callbackURI = "http://localhost:57119/Home/GetAccessToken";
        private const String URL_OAUTH_ACCOUNT = "http://localhost:53220/api/OAuthAccount";//"http://{0}/v1/contacts";
        private const String URL_OAUTH_CONTACT = "http://localhost:53220/api/OAuthFriend";//"http://{0}/v1/contacts";

        // GET api/Message/username?asd
        public OauthInfo GetToken(String id, [FromUri]String Password)
        {
            HttpWebRequest Request = null;
            String urlrequest = String.Empty;
            String requesttoken = String.Empty;
            try
            {
                //Get requesttoken
                String oauth_nonce = DateTime.Now.Millisecond.ToString();
                TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
                double unixTime = ts.TotalSeconds;
                String oauth_timestamp = unixTime.ToString();
                String oauth_signature = IndexManager.CONSUMERKEYSECRECT;
                urlrequest = String.Format("{0}?oauth_nonce={1}&oauth_timestamp={2}&oauth_consumer_key={3}&oauth_signature_method=PLAINTEXT&oauth_signature={4}&oauth_version=1.0&oauth_callback={5}",
                    URL_OAUTH_DIRECT, oauth_nonce, oauth_timestamp, IndexManager.CONSUMERKEY, oauth_signature, UriUtility.UrlEncode(callbackURI));
                Request = HttpWebRequest.Create(urlrequest.Trim()) as HttpWebRequest;
                Request.Accept = "text/plain";

                using (HttpWebResponse response = Request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        // Create Stream Reader                   
                        StreamReader reader = new StreamReader(response.GetResponseStream());
                        // Return                    
                        requesttoken = reader.ReadToEnd();
                        String[] rep = requesttoken.Split('&');
                        OauthInfo oauth = new OauthInfo(rep[0].Split('=')[1].ToString(), rep[1].Split('=')[1].ToString(), String.Empty);
                        oauth.RedirectURL = HttpUtility.UrlDecode(rep[3].Split('=')[1].Replace("\"", "").ToString());
                        return oauth;
                    }
                }
            }
            catch (Exception ex)
            {
                return null;
            }
            return null;
        }

        public String GetAccessToken([FromUri]String OauthToken, [FromUri] String OauthVerify, [FromUri] String UserName)
        {
            try
            {
                String oauth_nonce = DateTime.Now.Millisecond.ToString();
                TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
                double unixTime = ts.TotalSeconds;
                String oauth_timestamp = unixTime.ToString();
                String oauth_signature = IndexManager.CONSUMERKEYSECRECT;
                String urlrequest = String.Format("{0}?oauth_nonce={1}&oauth_timestamp={2}&oauth_consumer_key={3}&oauth_signature_method=PLAINTEXT&oauth_signature={4}&oauth_version=1.0&oauth_token={5}&oauth_verifier={6}",
                    URL_OAUTH_ACCESS_TOKEN, oauth_nonce, oauth_timestamp, IndexManager.CONSUMERKEY, oauth_signature, OauthToken, OauthVerify);
                HttpWebRequest Request = HttpWebRequest.Create(urlrequest.Trim()) as HttpWebRequest;
                Request.ContentType = "application/json;charset=utf-8";

                using (HttpWebResponse response = Request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        // Create Stream Reader                   
                        StreamReader reader = new StreamReader(response.GetResponseStream());
                        // Return                    
                        String resp = reader.ReadToEnd();
                        String[] rep = resp.Split('&');
                        String primaryID = UserName;
                        YahooInfo info = new YahooInfo(primaryID);
                        OauthInfo oauth = new OauthInfo(rep[0].Split('=')[1], rep[1].Split('=')[1], String.Empty);
                        oauth.Oauth_expires_in = rep[2].Split('=')[1].Replace("\"", "");
                        info.Oauth = oauth;
                        IndexManager.AddYahoo(info);
                        return "Success";
                    }
                }
            }
            catch (Exception ex)
            {
                return "Invalid";
            }
            return "";
        }

        // GET api/Yahoo/username
        public IEnumerable<YahooInfo> GetFriend(String id)
        {
            int index = IndexManager.FindYahooIndex(id.Trim());
            if (index != -1)
            {
                try
                {
                    YahooInfo yi = IndexManager.GetYahooInfo(index);
                    List<YahooInfo> lst = new List<YahooInfo>();
                    String urlrequest = URL_OAUTH_CONTACT + yi.Oauth.getHeader(IndexManager.CONSUMERKEY, IndexManager.CONSUMERKEYSECRECT);
                    HttpWebRequest Request = HttpWebRequest.Create(urlrequest.Trim()) as HttpWebRequest;
                    Request.Method = "GET";

                    using (HttpWebResponse response = Request.GetResponse() as HttpWebResponse)
                    {
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            // Create Stream Reader                   
                            StreamReader reader = new StreamReader(response.GetResponseStream());
                            // Return                    
                            String resp = reader.ReadToEnd();                          
                            JArray arr = JArray.Parse(resp.ToString());
                            foreach (JObject i in arr)
                            {
                                YahooInfo y = new YahooInfo(i["Username"].ToString());
                                if (i["IsOnl"].ToString() == "1")
                                    y.State = true;
                                lst.Add(y);
                            }
                            return lst;
                        }
                    }
                }
                catch (Exception ex)
                {
                    return null;
                }
            }
            return null;
        }

        public String PostLogout(String id)
        {
            //Login success
            int index = IndexManager.FindYahooIndex(id.Trim());
            if (-1 != index)
            {
                YahooInfo yi = IndexManager.GetYahooInfo(index);
                String urlrequest = URL_OAUTH_ACCOUNT + yi.Oauth.getHeader(IndexManager.CONSUMERKEY, IndexManager.CONSUMERKEYSECRECT);
                HttpWebRequest Request = HttpWebRequest.Create(urlrequest.Trim()) as HttpWebRequest;
                Request.Method = "DELETE";
                Request.ContentType = "application/json;charset=utf-8";

                using (HttpWebResponse response = Request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        // Create Stream Reader                   
                        IndexManager.RemoveYahoo(id.Trim());
                        return "sc";
                    }
                }
            }
            return "er";
        }      
    }
}
